//  数据库相关操作
const mysql = require('mysql2/promise')
const config = require('../config')

//  线程池  （连接池）
const pool = mysql.createPool({
    host:config.db.host,
    port:config.db.port,
    user:config.db.user,
    password:config.db.password,
    database:config.db.database
})

// 执行 sql 的方法  
const allServices = {
    async query(sql, values) {
        try {
            // 通过连接池连接 mysql
            const conn = await pool.getConnection()
            // 执行各种增删改查的 sql 语句
            const [rows, fields] = await conn.query(sql, values)
            // 释放连接
            pool.releaseConnection(conn)
            // 返回查询结果
            return Promise.resolve(rows)
        } catch (error) {
            return Promise.reject(error)
        }
    }
}

// 登录要执行的函数
const userLogin = (username, password) => {
    let _sql = `select * from user where username="${username}" and password="${password}";`
    return allServices.query(_sql)
}

const findUser = (username) => {
    let _sql = `select * from user where username="${username}";`
    return allServices.query(_sql)
}

// 注册要执行的函数
const userRegister = ({username, password, nickname, create_time}) => {
    let _sql = `insert into user (username, password, nickname, create_time) values ("${username}", "${password}", "${nickname}", "${create_time}");`
    return allServices.query(_sql)
}

// 根据类型查找日记列表数据
const findNoteListByType = (note_type, userId) => {
    let _sql = `select * from note where note_type="${note_type}" and user_id="${userId}";`
    return allServices.query(_sql)
}

module.exports = {
    findNoteListByType,
    userLogin,
    findUser,
    userRegister,
}